package org.suyafei.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.suyafei.strategy.ShardingDBConfig;
import org.suyafei.strategy.ShardingTableConfig;
import org.suyafei.utils.CommonUtil;

/**
 * @author 宿某人
 * @Date: 2021/12/16/5:43 下午
 * @Description:
 */
@Component
@Slf4j
public class ShortLinkComponent {
    private static final String CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    public String createShortLinkCode(String url) {

        long murmurHash = CommonUtil.murmurHash32(url);

        String code = encodeToBase62(murmurHash);
        return ShardingDBConfig.getPollingBPrefix(code) +code + ShardingTableConfig.getPollingBPrefix(code);


    }

    /**
     * 转换为62进制
     * @param param
     * @return
     */
    private String encodeToBase62(long param) {
        StringBuilder sb = new StringBuilder();

        do {
            int i = (int) (param % 62);
            sb.append(CHARS.charAt(i));
            param = param / 62;
            
        } while (param > 0);
        return sb.toString();
    }
}
